package com.example.testtdengine.controller;

import com.example.testtdengine.domain.parameter.WeatherParameter;
import com.example.testtdengine.domain.tdengine.Weather;
import com.example.testtdengine.service.WeatherService;
import com.example.testtdengine.utils.ResponseData;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author wz
 * @title
 * @date 2025/1/10 9:18
 */
@RestController
@RequestMapping("/weather")
public class WeatherController {

    @Resource
    private WeatherService weatherService;

    @GetMapping("/getByTemperature")
    public ResponseData getByTemperature(@RequestParam("temperature") Float temperature) {
        ResponseData result = ResponseData.ok();
        Weather weather = new Weather();
        weather.setTemperature(temperature);
        List<Weather> list = weatherService.lambdaQuery()
                .eq(Weather::getTemperature, weather.getTemperature())
                .list();
        result.putDataValue("data", list);
        return result;
    }

    @GetMapping("/getAfterTimestamp")
    public ResponseData getByTimestamp(@RequestParam("timestamp") String timestamp) throws ParseException {
        ResponseData result = ResponseData.ok();
        // 格式化时间为yyyy-MM-dd HH:mm:ss
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = dateFormat.parse(timestamp);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formatter = sdf.format(parse);
        List<Weather> list = weatherService.lambdaQuery()
                .ge(Weather::getTs, formatter)
                .list();
        result.putDataValue("data", list);
        return result;
    }

    @PostMapping("/save")
    public ResponseData save(@RequestBody WeatherParameter weatherParameter) {
        Weather weather = new Weather();
        BeanUtils.copyProperties(weatherParameter, weather);
        weather.setTs(new Timestamp(new Date().getTime()));
        weather.setTableName("weather1");
        weatherService.insert(weather);
        return ResponseData.ok();
    }

}
